package com.huang.transport.socket.server;

import com.huang.handler.RequestHandler;
import com.huang.registry.ServiceRegistry;
import com.huang.serializer.CommonSerializer;
import com.huang.transport.socket.util.ObjectReader;
import com.huang.transport.socket.util.ObjectWriter;
import com.huangwei.entity.RpcRequest;
import com.huangwei.entity.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * 处理RpcRequest的工作线程
 */
public class SocketRequestHandlerThread implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(SocketRequestHandlerThread.class);

    private Socket socket;
    private RequestHandler requestHandler;
    private CommonSerializer serializer;

    public SocketRequestHandlerThread(Socket socket, RequestHandler requestHandler, CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }

    /*
    线程的run方法，将接收到的二进制流转化为request对象，调用handle方法后
     */
    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            RpcRequest rpcRequest = (RpcRequest) ObjectReader.readObject(inputStream);
            Object result = requestHandler.handle(rpcRequest);
            RpcResponse<Object> response = RpcResponse.success(result,rpcRequest.getRequestId());
            ObjectWriter.writeObject(outputStream,response,serializer);
        } catch (IOException e){
            logger.error("调用或发送时有错误发生：",e);

        }
    }
}
